<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 题目内容 -->
      <el-form-item label="题目内容" prop="queContent">
        <el-input
          v-model="formData.queContent"
          type="textarea"
          :rows="3"
          placeholder="请输入题干"
        />
      </el-form-item>
      
      <!-- 区分度 -->
      <el-form-item label="区分度" prop="discrimination">
        <el-input-number v-model="formData.discrimination" class="!w-200px" />
      </el-form-item>

      <!-- 选项配置 -->
      <el-form-item label="选项">
        <div class="w-full">
          <!-- 表头 -->
          <div class="flex items-center gap-10px mb-10px text-14px font-500 text-gray-600">
            <div style="width: 80px">选项名称</div>
            <div style="flex: 1">选项内容</div>
            <div style="width: 150px">选项得分</div>
            <div style="width: 150px">难易度</div>
            <div style="width: 80px">操作</div>
          </div>
          
          <!-- 选项列表 -->
          <div v-for="(option, index) in formData.options" :key="index" class="flex items-center gap-10px mb-10px">
            <el-input v-model="option.optionName" placeholder="选项名称" style="width: 80px" />
            <el-input v-model="option.optionText" placeholder="选项内容" style="flex: 1" />
            <el-input-number v-model="option.optionScore" placeholder="选项得分" style="width: 150px" />
            <el-input-number v-model="option.difficulty" placeholder="难易度" style="width: 150px" />
            <div style="width: 80px">
              <el-button type="danger" size="small" @click="removeOption(index)" class="text-red-500">删除</el-button>
            </div>
          </div>
          
          <!-- 添加选项按钮 -->
          <el-button type="primary" size="small" @click="addOption" class="mt-10px">添加选项</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as QuestionApi from '@/api/pm/tm'

defineOptions({ name: 'QuestionForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  storeId: undefined,
  queContent: '',
  type: 'single',
  markingType: 'objective',
  score: 1,
  discrimination: 0,
  options: [
    { optionName: 'A', optionText: '', optionScore: 0, difficulty: 0 },
    { optionName: 'B', optionText: '', optionScore: 0, difficulty: 0 },
    { optionName: 'C', optionText: '', optionScore: 0, difficulty: 0 },
    { optionName: 'D', optionText: '', optionScore: 0, difficulty: 0 },
    { optionName: 'E', optionText: '', optionScore: 0, difficulty: 0 }
  ]
})
const formRules = reactive({
  queContent: [{ required: true, message: '题干不能为空', trigger: 'blur' }],
  discrimination: [{ required: true, message: '区分度不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, storeId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.storeId = storeId
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await QuestionApi.getQuestionDetail(id)
      Object.assign(formData.value, data)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await QuestionApi.addQuestion(data)
      message.success(t('common.createSuccess'))
    } else {
      await QuestionApi.updateQuestion(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    storeId: undefined,
    queContent: '',
    type: 'single',
    markingType: 'objective',
    score: 1,
    discrimination: 0,
    options: [
      { optionName: 'A', optionText: '', optionScore: 0, difficulty: 0 },
      { optionName: 'B', optionText: '', optionScore: 0, difficulty: 0 },
      { optionName: 'C', optionText: '', optionScore: 0, difficulty: 0 },
      { optionName: 'D', optionText: '', optionScore: 0, difficulty: 0 },
      { optionName: 'E', optionText: '', optionScore: 0, difficulty: 0 }
    ]
  }
  formRef.value?.resetFields()
}

/** 添加选项 */
const addOption = () => {
  const nextName = String.fromCharCode(65 + formData.value.options.length) // A, B, C...
  formData.value.options.push({
    optionName: nextName,
    optionText: '',
    optionScore: 0,
    difficulty: 0
  })
}

/** 删除选项 */
const removeOption = (index: number) => {
  if (formData.value.options.length > 2) {
    formData.value.options.splice(index, 1)
  } else {
    message.warning('至少需要保留2个选项')
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
</script>
